import click
import os
import platform
import sys
from collections import OrderedDict

import json
import pandas as pd
from common.database import SessionLocal
from datetime import datetime, time

# from app.service_quality.handlers.qos_host_date_handler import QosHostDateHandler
# from app.service_quality.handlers.qos_host_info_handler import QosHostInfoHandler
from app.service_quality.handlers.qos_host_disk_handler import QosHostDiskHandler
from app.service_quality.handlers.qos_server_info_handler import QosServerInfoHandler
from app.service_quality.handlers.qos_server_date_handler import QosServerDateHandler
from app.service_quality.models.qos_server_info import QosServiceInfo

from common.welab_k8s.k8s_prometheus import K8sPrometheus

from core.logger import logger


class QosClick(object):
    def __init__(self):
       self.session = SessionLocal()
       self.k8s_prometheus = K8sPrometheus()


    def __del__(self):
        self.session.close()


    # def host_date_sync_from_prom(self, data):
    #     """
    #     同步服务器监控数据到数据库
    #     """
    #     qos_host_date_handler = QosHostDateHandler()
    #     qos_host_date_handler.task_update_host_date_handle(self.session, data)
        
        
    # def host_info_sync_from_aliyun(self):
    #     """
    #     同步服务器信息到数据库
    #     """
    #     qos_host_info_handler = QosHostInfoHandler()
    #     qos_host_info_handler.task_update_host_info_handle(self.session)


    def host_disk_sync_from_aliyun(self):
        """
        同步磁盘信息到数据库
        """
        qos_host_disk_handler = QosHostDiskHandler()
        qos_host_disk_handler.task_update_host_disk_handle(self.session)


    # def host_date_to_excel(self, data):
    #     """
    #     导出服务器质量数据到excel
    #     """
    #     qos_host_date_handler = QosHostDateHandler()
    #     status, result = qos_host_date_handler.get_host_date_search(self.session, data["quality_date"], 1, 2000, "all", "")
    #     if not status:
    #         logger.warning(f"get host date search failed")
    #         return False

    #     df = pd.DataFrame(result["items"])
    #     df.to_excel(f"服务器监控数据{data['quality_date']}.xlsx", index=False)
    #     logger.info("export all host date info success")
    #     return True


    def server_info_sync_from_k8s(self):
        """
        从k8s同步容器服务信息到数据库
        """
        qos_server_info_handler = QosServerInfoHandler()
        qos_server_info_handler.task_update_container_server_info_handle(self.session)


    def server_info_sync_from_excel(self, file_path):
        """
        从excel同步物理服务信息到数据库
        """
        try:
            servers_info = []
            df = pd.read_excel(file_path, "Sheet1")
            for i in df.index.values:
                row_data = df.loc[i].to_dict()
                row_data["deploy_nodes"] = row_data["deploy_nodes"].split()
                servers_info.append(row_data)

            for server_info in servers_info:
                server_object = QosServiceInfo.get_object_by_name(self.session, server_info["name"])
                if not server_object:
                    # 如果不存在， 则新增
                    result = QosServiceInfo.add(self.session, server_info)
                else:
                    # 如果存在， 则更新
                    server_info["uuid"] = server_object.uuid
                    result = QosServiceInfo.update(self.session, server_info)
                if not result:
                    logger.error(f"{server_info['name']} add success")
                    return False

                logger.info(f"{server_info['name']} add success")
        except Exception as e:
            logger.exception(e)
            return False

        logger.info("update tag department from excel success")
        return True



    def server_date_sync_from_prom(self, data):
        """
        同步应用服务监控数据到数据库
        """
        qos_server_date_handler = QosServerDateHandler()
        qos_server_date_handler.task_update_server_date_handle(self.session, data)



    def server_date_to_excel(self, data):
        """
        导出应用服务质量数据到excel
        """
        qos_server_date_handler = QosServerDateHandler()
        status, result = qos_server_date_handler.get_server_date_search(self.session, data["quality_date"], 1, 2000, "all", "")
        if not status:
            logger.warning(f"get server date search failed")
            return False

        df = pd.DataFrame(result["items"])
        df.to_excel(f"应用服务监控数据{data['quality_date']}.xlsx", index=False)
        logger.info("export all server date info success")
        return True

    def qos_server_tuiguang_to_excel(self, quality_date):
        qos_server_date_handler = QosServerDateHandler()
        status = qos_server_date_handler.get_container_cpu_change(self.session, quality_date)
        if not status:
            logger.warning(f"get container cpu change failed")
            return False
        logger.warning(f"get container cpu change success")
        return True

    def add_host_disk_from_excel(self, file_name):
        hosts_info = []
        df = pd.read_excel(file_name, "Sheet1")
        for i in df.index.values:
            row_data = df.loc[i].to_dict()
            hosts_info.append(row_data)

        for host_info in hosts_info:
            # 数据盘大小
            disk_total_expr = "node_filesystem_size_bytes{" + f"instance='{host_info['ip']}:9100'" + ",mountpoint='/data'}"
            disk_total_data = self.k8s_prometheus.query_prometheus_data(disk_total_expr)
            if not disk_total_data:
                logger.error(f"cpu_spec_expr:{disk_total_expr}, query prometheus data failed or None")
                continue
            host_info["数据盘大小"] = int(float(disk_total_data[0]["value"][1])/1024/1024/1000/10)*10 if disk_total_data else 0

            # 数据盘的使用率
            disk_usage_expr = "PrometheusRecordECSHostDiskUsage{" + f"instance='{host_info['ip']}:9100'" + ",mountpoint='/data'}"
            disk_usage_data = self.k8s_prometheus.query_prometheus_data(disk_usage_expr)
            if not disk_usage_data:
                logger.error(f"cpu_spec_expr:{disk_usage_expr}, query prometheus data failed or None")
                continue
            host_info["数据盘使用率"] = round(float(disk_usage_data[0]["value"][1]), 2) if disk_usage_data else 0


        df = pd.DataFrame(hosts_info)
        df.to_excel(f"disk_{file_name}", index=False)
        logger.info("write info to_excel success")




    def test(self):
        QosServiceInfo.get_container_cpu_by_department(self.session)



def main():
    qos_click = QosClick()

    # 同步主机的监控数据
    data = {"quality_date":"2023-03-02"}
    # qos_click.server_info_sync_from_k8s()
    qos_click.server_date_sync_from_prom(data)
    # qos_click.server_date_to_excel(data)

    # qos_click.host_date_sync_from_prom(data)
    # qos_click.host_date_to_excel(data)
    # qos_click.add_host_disk_from_excel("k8s_node.xlsx")
    # qos_click.host_info_sync_from_aliyun()
    # qos_click.host_disk_sync_from_aliyun()



    # qos_click.server_info_sync_from_excel("物理服务梳理.xlsx")

    # qos_click.test()




if __name__ == "__main__":
    main()
